package com.example.kotlinExample.socket

import com.google.gson.Gson
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import java.util.concurrent.ConcurrentHashMap
import javax.websocket.OnClose
import javax.websocket.OnMessage
import javax.websocket.OnOpen
import javax.websocket.Session
import javax.websocket.server.PathParam
import javax.websocket.server.ServerEndpoint


/**
 *
 *
 * @author liliang
 */
@ServerEndpoint("/websocket/{name}")
@Component
class WebSocket {

    /**
     * 与某个客户端的连接对话，需要通过它来给客户端发送消息
     */
    private lateinit var session: Session

    /**
     * 标识当前连接客户端的用户名
     */
    private lateinit var name: String

    /**
     * 用于存所有的连接服务的客户端，这个对象存储是安全的
     */
    companion object {
        val webSocketSet: ConcurrentHashMap<String, WebSocket> = ConcurrentHashMap()
    }

    private val restTemplate = RestTemplate()

    @OnOpen
    fun onOpen(session: Session, @PathParam(value = "name") name: String) {
        this.session = session
        this.name = name
        // name是用来表示唯一客户端，如果需要指定发送，需要指定发送通过name来区分
        webSocketSet[name] = this
        println("[WebSocket] 连接成功，当前连接人数为：=${webSocketSet.size}")
    }

    @OnClose
    fun onClose() {
        webSocketSet.remove(name)
        println("[WebSocket] 退出成功，当前连接人数为：=${webSocketSet.size}")
    }

    @OnMessage
    fun onMessage(message: String) {
        println("[WebSocket] 收到消息：${message}")
//        val forEntity = restTemplate.getForObject("http://www.tuling123.com/openapi/api?key=19c44544782a4f8d9205ff0a49d232df&info=$message", String::class.java)
//        val text = Gson().fromJson(forEntity, ResultMsg::class.java).text
        //判断是否需要指定发送，具体规则自定义
        appointSending(name, message)
    }

    /**
     * 群发
     * @param message
     */
    fun groupSending(message: String) {
        for (name in webSocketSet.keys) {
            try {
                webSocketSet[name]!!.session.basicRemote.sendText(message)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 指定发送
     * @param name
     * @param message
     */
    fun appointSending(name: String, message: String) {
        try {
            webSocketSet[name]?.session?.basicRemote?.sendText(message)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}